package com.sfac.springboot.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @author jzq
 * @date 2022/8/22 17:29
 */
@SuppressWarnings({"all"})

@WebFilter
public class ParamFilter implements Filter {

    public static final Logger LOGGER = LoggerFactory.getLogger(ParamFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("=========do init==========");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        LOGGER.debug("=========do filter==========");

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

//        构建wrapper对象的getParameter方法，替换掉赃字符串
        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(req) {
            @Override
            public String getParameter(String name) {
                String value = super.getParameter(name);
                return StringUtils.isNotBlank(value) ?
                        value.replace("fuck", "*****") : "";

            }

            @Override
            public String[] getParameterValues(String name) {
                String[] values = super.getParameterValues(name);
                if (values == null) {
                    return new String[]{};
                }
                return Arrays.asList(values)
                        .stream()
                        .map(item -> item.replaceAll("fuck", "****"))
                        .toArray(String[]::new);
            }
        };

        filterChain.doFilter(wrapper, servletResponse);
    }

    @Override
    public void destroy() {
        LOGGER.debug("=========do filter==========");
    }

}

